var express = require('express');
var router = express.Router();
var MongoClient=require('mongodb').MongoClient;
var DB_CONN_STR='mongodb://127.0.0.1:27017/vue';
var async=require('async');

/* GET users listing. */
router.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/reg', function(req, res, next) {
  MongoClient.connect(DB_CONN_STR,function(err,db){
    if (err) {
      res.send('网络异常')
    }else{
      console.log('第一步,链接上mongo');
      var conn = db.collection('eleme');
      async.series([
        //做查询
        function(cb){
          conn.find({username:req.query.username}).count(function(err,num){
            if (err) {
              console.log('失败')
              cb('err','查询失败');
            }else{
              if (num>0) {
                cb('null','登录成功')
                console.log('登录成功')
              }else{
                cb(null)
              }
            }
          })
        },
        function(cb){
          conn.save(req.query,function(err,info){
            if (err) {
              cb('err','新增失败')
            }else{
              cb('null','注册成功')
              console.log('储存成功')
            }
          })
        }
      ],function(err,result){
        if (err) {
          res.send(result);
        }else{
          res.send('成功');
          console.log('第三步')
        }
      })
    }
  })
});

module.exports = router;
